package com.frxuexi.shop.view

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.alipay.MyPay
import com.frxuexi.lib_base.entity.Item0
import com.frxuexi.lib_base.entity.OrderBean
import com.frxuexi.lib_base.entity.PayOrderReqBean
import com.frxuexi.lib_base.entity.RefundOrderBean
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.lib_base.utils.GlideUtils
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.OrderAdapter
import com.frxuexi.shop.databinding.ActivityOrderBinding
import com.frxuexi.shop.intent.OrderIntent
import com.frxuexi.shop.viewmodel.OrderViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = "/shop/OrderActivity")
@AndroidEntryPoint
class OrderActivity : BaseActivity<ActivityOrderBinding, OrderIntent, OrderViewModel>() {
    override val binding: ActivityOrderBinding by lazy { ActivityOrderBinding.inflate(layoutInflater) }
    override val vm: OrderViewModel by viewModels<OrderViewModel>()
    val orderAdapter by lazy { OrderAdapter() }

    var position = 0
    var index=0
    lateinit var bean: Item0

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                val bean = it.data as OrderBean
                                bean.list.forEach { it.itemType = position }
                                orderAdapter.data.clear()
                                orderAdapter.addData(bean.list)
                                orderAdapter.notifyDataSetChanged()
                            }

                            RequestType.DELETE -> {
                                vm.sendIntent(OrderIntent.getOrders(index))
                            }

                            RequestType.UPDATE -> {
                                vm.sendIntent(OrderIntent.getOrders(index))
                            }
                            RequestType.REFUND->{
                                ToastUtils.showLong("退货成功")
                                vm.sendIntent(OrderIntent.getOrders(index))
                            }


                            else -> {}

                        }

                    }

                    is UiState.onError -> {}
                    UiState.onLoading -> {}
                }
            }
        }
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        binding.orderTab.apply {
            addTab(newTab().setText("待付款"), true)
            addTab(newTab().setText("待发货"))
            addTab(newTab().setText("待收货"))
            addTab(newTab().setText("待评论"))
            addTab(newTab().setText("已完成"))
            addTab(newTab().setText("售后/退货"))
            addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    position = tab?.position!!
                    index =
                        if (tab?.position == 5) -3 else if (tab?.position == 3) 1 else tab?.position!!
                    vm.sendIntent(OrderIntent.getOrders(index))
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })
        }

        binding.orderRv.apply {
            adapter = orderAdapter
            layoutManager = LinearLayoutManager(this@OrderActivity)
        }
        vm.sendIntent(OrderIntent.getOrders(0))

        orderAdapter.addChildClickViewIds(
            R.id.order_cancel,
            R.id.order_pay,
            R.id.order_comment,
            R.id.order_tui
        )
        orderAdapter.setOnItemChildClickListener { adapter, view, position ->
            bean = orderAdapter.data.get(position)
            when (view.id) {
                R.id.order_cancel -> {
                    vm.sendIntent(OrderIntent.cancelOrder(bean.id))
                }

                R.id.order_pay -> {
                    MyPay.payV2("100", this)
                }

                R.id.order_comment -> {
//                    ArouterManager.nav(this,"/shop/CommentActivity")
                    ARouter.getInstance().build("/shop/CommentActivity")
                        .withSerializable("order", bean).navigation()
                }

                R.id.order_tui -> {

                    val window = PopupWindow(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    )
                    val pop = LayoutInflater.from(this).inflate(R.layout.pop_tui, null)
                    window.contentView = pop
                    pop.findViewById<TextView>(R.id.tui_title)
                        .setText(bean.orderInfoList[0].storeName)
                    pop.findViewById<TextView>(R.id.tui_num)
                        .setText("数量：" + bean.orderInfoList[0].cartNum.toString())
                    GlideUtils.loadRoundImage(
                        bean.orderInfoList[0].image,
                        pop.findViewById<ImageView>(R.id.tui_iv)
                    )

                    pop.findViewById<ImageView>(R.id.tui_close).setOnClickListener {
                        window.dismiss()
                    }
                    window.showAtLocation(view, Gravity.BOTTOM, 0, 0)

                    pop.findViewById<TextView>(R.id.tui_btn).setOnClickListener {
                        val refundOrderBean = RefundOrderBean(
                            0,
                            "不想要了",
                            "",
                            "不合适",
                            bean.orderId
                        )
                        vm.sendIntent(OrderIntent.refundOrder(refundOrderBean))
                        window.dismiss()
                    }
                }

            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun payResult(result: String) {
        if (result == "payOk") {
            ToastUtils.showLong("支付成功")
            val reqBean =
                PayOrderReqBean("", bean.orderId, "alipay", "yue", 0, bean.id.toString())
            vm.sendIntent(OrderIntent.payOrder(reqBean))
        }
    }

}